package com.hxd.mall.utils.local

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.util.Log
import android.view.View
import android.webkit.URLUtil
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast

import androidx.core.content.ContextCompat
import com.hexin.locallibrary.permssion.PermissionGrantedCallback
import com.hexin.locallibrary.permssion.PermissionList
import com.hexin.locallibrary.permssion.PermissionUtils

import com.hexin.locallibrary.updata.DownloadUtil
import com.hexin.locallibrary.updata.InstallUtils
import com.hxd.mall.utils.open.ToastUtil

import java.io.File
import java.util.ArrayList

import okhttp3.HttpUrl

import com.hxd.mall.constant.HxdGlobalInfo.instance

class AppUpdateUtils {

    private var tvUpdate: TextView? = null
    private var pbUpdateDialog: ProgressBar? = null
    private var tvProgressUpdate: TextView? = null
    private var close: ImageView? = null

    //是否正在下载
    var isLoading = false
    private var loadingDialog: Dialog? = null
    private var is_force: String? = null

    @SuppressLint("SetTextI18n")
    fun showUpdateDialog(activity: Activity, versionContrastInfo: ArrayList<String>?, is_force: String, versionName: String, apk_url: String) {
        this.is_force = is_force
        if (loadingDialog == null) {
            loadingDialog = Dialog(activity, com.hexin.locallibrary.R.style.TranslucentBackground)
            val inflate = View.inflate(activity, com.hexin.locallibrary.R.layout.dialog_update, null)
            val ll_content = inflate.findViewById<LinearLayout>(com.hexin.locallibrary.R.id.ll_content)
            val version_name = inflate.findViewById<TextView>(com.hexin.locallibrary.R.id.version_name)
            version_name.text = "V$versionName"
            close = inflate.findViewById(com.hexin.locallibrary.R.id.close)
            tvUpdate = inflate.findViewById(com.hexin.locallibrary.R.id.tv_update)
            pbUpdateDialog = inflate.findViewById(com.hexin.locallibrary.R.id.pb_updatedialog)
            tvProgressUpdate = inflate.findViewById(com.hexin.locallibrary.R.id.tv_progress_updata)
            if (versionContrastInfo != null && versionContrastInfo.size > 0) {
                for (i in versionContrastInfo.indices) {
                    val textView = TextView(activity)
                    if (versionContrastInfo.size != 1 ) {
                        textView.text = (i + 1).toString() + "、" + versionContrastInfo[i]
                    }else{
                        textView.text =  versionContrastInfo[i]
                    }
                    textView.setTextColor(ContextCompat.getColor(activity, com.hexin.locallibrary.R.color.color_444444))
                    textView.textSize = 12f
                    textView.setPadding(0, dip2px(activity, 7), 0, 0)
                    ll_content.addView(textView)
                }
            }
            if ("2" != is_force) {
                close!!.visibility = View.VISIBLE
            }
            close!!.setOnClickListener { loadingDialog!!.dismiss() }
            tvUpdate!!.setOnClickListener(View.OnClickListener {
                if (!URLUtil.isHttpUrl(apk_url) && !URLUtil.isHttpsUrl(apk_url)) {
                    ToastUtil.showToast("下载地址不合法")
                    return@OnClickListener
                }
                tvUpdate!!.visibility = View.INVISIBLE
                close!!.visibility = View.GONE
                pbUpdateDialog!!.visibility = View.VISIBLE
                tvProgressUpdate!!.visibility = View.VISIBLE
                httpDownload(activity, apk_url, loadingDialog, false)
            })
            loadingDialog!!.setCancelable(false)
            loadingDialog!!.setContentView(inflate)
        }
        if (loadingDialog != null && !loadingDialog!!.isShowing) {
            loadingDialog!!.show()
        }
    }

    private fun dip2px(context: Context, dip: Int): Int {
        val scale = context.resources.displayMetrics.density
        return (dip * scale + 0.5f).toInt()
    }

    /**
     * 使用okhttp 下载
     *
     * @param activity
     * @param downUrl
     * @param authorestampdialog
     * @param sense
     */
    fun httpDownload(activity: Activity, downUrl: String, authorestampdialog: Dialog?, sense: Boolean) {
        DownloadUtil.get().download(instance, downUrl, object : DownloadUtil.OnDownloadListener {
            override fun onStart() {
                Log.i("down", "onStart")
                isLoading = true
                if (!sense) {
                    pbUpdateDialog!!.progress = 0
                    pbUpdateDialog!!.visibility = View.VISIBLE
                }
            }

            override fun onDownloadSuccess(file: File) {
                Log.i("down", "onDownloadSuccess")
                isLoading = false
                if (!sense) {
                    authorestampdialog?.dismiss()
                }

                PermissionUtils.permissionCheck(activity, PermissionList.permission_sdcardRW, "", object : PermissionGrantedCallback {
                    override fun granted() {
                        InstallUtils.installApk(activity, file)
                    }

                    override fun denied() {
                        if ("2" == is_force) {
                          StackManageUtil.closeAll()
                        }

                    }
                })

            }

            override fun onDownloading(progress: Int) {
                Log.i("down", "onDownloading$progress")
                isLoading = true
                if (!sense) {
                    pbUpdateDialog!!.progress = progress
                    tvProgressUpdate!!.text = "$progress%"
                }
            }

            override fun onDownloadFailed(e: Exception) {
                Log.i("down", "onDownloadFailed")
                isLoading = false
                if (!sense) {
                    Toast.makeText(activity, e.message, Toast.LENGTH_LONG).show()
                    if (is_force != "2") {
                        close!!.visibility = View.VISIBLE
                    }
                    tvUpdate!!.visibility = View.VISIBLE
                    tvProgressUpdate!!.visibility = View.GONE
                    pbUpdateDialog!!.visibility = View.GONE
                }
            }
        })
    }

    fun cancel() {
        DownloadUtil.get().removeHandler()
    }
}
